import { defineStore } from 'pinia'
import {
  createChatRoom,
  getChatRooms,
  sendMessage,
  getChatMessages
} from '@/services/chatService'
import { ref } from 'vue'

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatRooms: [],
    currentRoomId: null,
    messages: ref([])
  }),

  actions: {
    async fetchChatRooms() {
      try {
        const rooms = await getChatRooms()
        this.chatRooms = rooms
        return rooms // 返回获取的房间列表
      } catch (error) {
        console.error('获取聊天房间失败:', error)
        throw error
      }
    },

    async createChatRoom() {
      const newRoom = await createChatRoom()
      this.currentRoomId = newRoom
      this.messages.value = ref([])
      return newRoom
    },

    async loadChatMessages(roomId) {
      this.currentRoomId = roomId
      try {
        const messageList = await getChatMessages(roomId)
        this.chatRooms = messageList
        return messageList
      } catch (error) {
        console.error('获取聊天记录失败:', error)
        throw error
      }
    },

    async sendChatMessage(roomId, message) {
      const response = await sendMessage(roomId, message)
      this.messages.value.push(
        { role: 'user', content: message },
        { role: 'assistant', content: response }
      )
      return this.messages.value
    }
  }
})
